package com.geekerp.authorization_server.service;

import com.geekerp.authorization_server.pojo.Oauth2BasicUser;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class Oauth2BasicUserServiceImpl implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 在Security中“username”就代表了用户登录时输入的账号，在重写该方法时它可以代表以下内容：账号、手机号、邮箱、姓名等
        // “username”在数据库中不一定非要是一样的列，它可以是手机号、邮箱，也可以都是，最主要的目的就是根据输入的内容获取到对应的用户信息，如下方所示
        // 通过传入的账号信息查询对应的用户信息
        Oauth2BasicUser basicUser = new Oauth2BasicUser();
        basicUser.setId(1);
        basicUser.setName("云逸");
        basicUser.setAccount("admin");
        basicUser.setPassword("$2a$10$K7nVcC.75YZSZU1Fq6G6buYujG.dolGYGPboh7eQbtkdFmB0EfN5K");
        basicUser.setMobile("17683906001");
        basicUser.setEmail("17683906001@163.com");
        basicUser.setDeleted(false);
        if (basicUser == null) {
            throw new UsernameNotFoundException("账号不存在");
        }
//
//        // 通过用户角色关联表查询对应的角色
//        List<SysUserRole> userRoles = sysUserRoleMapper.selectList(Wrappers.lambdaQuery(SysUserRole.class).eq(SysUserRole::getUserId, basicUser.getId()));
//        List<Integer> rolesId = Optional.ofNullable(userRoles).orElse(Collections.emptyList()).stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
//        if (ObjectUtils.isEmpty(rolesId)) {
//            return basicUser;
//        }
//        // 通过角色菜单关联表查出对应的菜单
//        List<SysRoleAuthority> roleMenus = sysRoleAuthorityMapper.selectList(Wrappers.lambdaQuery(SysRoleAuthority.class).in(SysRoleAuthority::getRoleId, rolesId));
//        List<Integer> menusId = Optional.ofNullable(roleMenus).orElse(Collections.emptyList()).stream().map(SysRoleAuthority::getAuthorityId).collect(Collectors.toList());
//        if (ObjectUtils.isEmpty(menusId)) {
//            return basicUser;
//        }
//
//        // 根据菜单ID查出菜单
//        List<SysAuthority> menus = sysAuthorityMapper.selectBatchIds(menusId);
//        Set<CustomGrantedAuthority> authorities = Optional.ofNullable(menus).orElse(Collections.emptyList()).stream().map(SysAuthority::getUrl).map(CustomGrantedAuthority::new).collect(Collectors.toSet());
//        basicUser.setAuthorities(authorities);
        return basicUser;
    }
}
